package com.sunwayworld.basemodule.business.ordertask.validators;

import com.sunwayworld.basemodule.business.ordertask.bean.LimsOrderTaskBean;
import com.sunwayworld.basemodule.business.ordertask.service.LimsOrderTaskService;
import com.sunwayworld.basemodule.business.result.bean.LimsRunBean;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.validator.data.DataValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsRunSubmitValidator implements DataValidator {

    @Autowired
    private LimsOrderTaskService orderTaskService;

    @Override
    public boolean doValid(Object... args) {
        RestJsonWrapperBean wrapper = (RestJsonWrapperBean) args[0];
        boolean result = true;
        List<LimsRunBean> runBeans = wrapper.parse(LimsRunBean.class);
        List<Long> runIds = runBeans.stream().map(LimsRunBean::getId).collect(Collectors.toList());

        List<LimsOrderTaskBean> taskBeans = orderTaskService.selectListByFilter(SearchFilter.instance()
                .match("runId", runIds).filter(MatchPattern.OR));

        for (LimsRunBean runBean : runBeans) {
            Optional<LimsOrderTaskBean> optional = taskBeans.stream().filter(s ->
                    s.getRunId().equals(runBean.getId())).findAny();
            if (!optional.isPresent()) {
                this.addConstraintViolation(runBean.getRunCode()+":"+I18nHelper.getMessage("RUN.SUBBMIT.CHECK_TASK_NOTEMPTY"));
                result = false;
            }
        }
        return result;
    }
}
